package com.youku.mson.serializer;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JsonSerializerFactory {

	private static final Map<Class<?>, JsonSerializer> config;

	static {
		config = new HashMap<>();

		put(String.class, new StringSerializer());
		put(byte.class, new NumberSerializer());
		put(short.class, new NumberSerializer());
		put(int.class, new NumberSerializer());
		put(long.class, new NumberSerializer());
		put(float.class, new NumberSerializer());
		put(double.class, new NumberSerializer());
	}

	public static JsonSerializer getSerializer(Class<?> targetClass) {
		JsonSerializer serializer = get(targetClass);
		if (serializer == null) {
			if (List.class.isAssignableFrom(targetClass)) {
				put(targetClass, new ListSerializer());
			} else if (Map.class.isAssignableFrom(targetClass)) {
				put(targetClass, new MapSerializer());
			} else if (Number.class.isAssignableFrom(targetClass)) {
				put(targetClass, new NumberSerializer());
			} else if (targetClass.isArray()) {
				put(targetClass, new ArraySerializer());
			} else {
				put(targetClass, new ObjecSerializer());
			}
			return get(targetClass);
		} else {
			return serializer;
		}
	}

	private static void put(Class<?> targetClass, JsonSerializer serializer) {
		config.put(targetClass, serializer);
	}

	private static JsonSerializer get(Class<?> targetClass) {
		return config.get(targetClass);
	}

}
